package com.my.screenadapter.View;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;

public class NumberEditText extends EditText {

    public NumberEditText(Context context) {
        super(context);
    }

    public NumberEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NumberEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public boolean isRun = false;
    public boolean hasSet = false;
    private String d = "";

    public void setNumberFormat(final boolean Open) {
        hasSet = Open;
        NumberEditText.this.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (hasSet) {
                    if (isRun) {
                        isRun = false;
                        return;
                    }
                    isRun = true;
                    d = "";
                    String newStr = s.toString();
                    newStr = newStr.replace(" ", "");

                    int index = 0;
                    while (index < newStr.length()) {
                        if (newStr.substring(index, index + 1).equals("-") && index == 0) {
                            d += (newStr.substring(index, index + 1));
                        } else if (!(newStr.substring(index, index + 1).equals("-")) && index != 0) {
                            d += (newStr.substring(index, index + 1));
                        }
                        index++;
                    }
                    d += (newStr.substring(index, newStr.length()));
                    NumberEditText.this.setText(d);
                    NumberEditText.this.setSelection(d.length());
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
}